import db from "../models/index.js";
import {getNow} from "../utils/utils.js";
import {config} from "../config/index.js";
import {Op} from "sequelize";

let captchaNew = db.captchaNew;
let captchaNewDao = {};

// 新增验证码
captchaNewDao.add = (email, code, type, t) => {
  code = (code + "").toUpperCase();
  let deadline = getNow() + config.CAPTCHA_DEADLINE;
  return captchaNew.create({email, code, type, deadline,}, {transaction: t});
};

// 验证用户的某一类型的验证码是否正确 带事务
captchaNewDao.verify = async (email, type, code, t) => {
  code = (code + "").toUpperCase();
  let result = await captchaNew.count({
      where: {email, type, code, deadline: {[Op.gt]: getNow()}},
      transaction: t
    });
  return result > 0;
};

// 删除用户的某一类型的验证码
captchaNewDao.delete = (email, type, t) => {
  return captchaNew.destroy({
      where: {email, type},
      transaction: t
    });
};

// 更新数据库该类型的验证码 以及最后时间
captchaNewDao.updateOrCreate = async (email, type, code, t) => {
  code = (code + "").toUpperCase();
  let deadline = getNow() + config.CAPTCHA_DEADLINE;
  let count = await captchaNew.count({where: {email, type}});
  let isExist = count > 0;
  if(isExist) {
    return captchaNew.update({code, deadline}, {where: {email, type}, transaction: t});
  }
  return captchaNew.create({code, deadline, type, email}, {transaction: t});
};
export default captchaNewDao;
